﻿using System;
using System.Collections.Generic;
using WeiTap.Restful;
using BrnMall.Manager.Domain.Store;
using BrnMall.Manager.Manager.Store;
using Newtonsoft.Json;
using BrnMall.Sms;
using QiDong.PC.Api.Models;
using System.Linq;
using QIDong.WeApp.Models;
using BrnMall.Services;
using BrnMall.Manager.Domain.Product;
using BrnMall.Manager.Manager.Product;
using BrnMall.Manager.Domain.PC;
using System.Text;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    /// PC网站接口
    /// </summary>
    public class PCController : WebApi
    {
        /// <summary>
        /// 添加用户联系信息
        /// </summary>
        /// <param name="storeid">店铺id</param>
        /// <param name="fullname">客户名字</param>
        /// <param name="phone">联系方式</param>
        /// <param name="companyname">所在单位</param>
        /// <param name="discription">留言内容</param>
        /// <param name="source"></param>
        /// <returns></returns>
        public string usermsg(int storeid, string fullname, string phone, string companyname, string discription, string source = "")
        {
            try
            {
                ////验证发送的验证码是否正确或是否过期
                //bool re = SMSHelper.ValidateCode(phone, valicode);
                var Consults = PcConsultManager.GetConsult(phone);
                if (Consults == null)
                {
                    //店铺信息
                    var info = Stores.GetStoreById(storeid);
                    var to = info.Email;  //店铺邮箱
                    string subject = string.Format("{0}访问你了你的网站", fullname);
                    StringBuilder body = new StringBuilder();
                    body.AppendFormat("客户所处单位：{0},", companyname);
                    body.AppendFormat("联系电话电话：{0},", phone);
                    body.AppendFormat("留言内容：{0}。", discription);
                    body.AppendFormat("访问时间：{0}", DateTime.Now);
                    bool res = Emails.SendEmail(to, subject, body.ToString());
                    if (res == true)
                    {
                        Consults = new PcConsult
                        {
                            Storeid = storeid,
                            CompanyName = companyname,
                            FullName = fullname,
                            Phone = phone,
                            Discription = discription,
                            Source = source,
                            Addtime = DateTime.Now
                        };
                        bool result = PcConsultManager.AddConsult(Consults);
                        if (result == true)
                            return "success";
                        else
                            return "网络超时，请稍后再试！";
                    }
                    else { return "网络超时，请稍后再试！"; }
                }
                else
                {
                    return "sub";
                }
            }
            catch (Exception e)
            {
                throw new ApiException(ExceptionCode.DataError, e.Message);
            }
        }

        public string GetUserMsg(string phone)
        {
            var con = PcConsultManager.GetConsult(phone);
            return JsonConvert.SerializeObject(con);
        }

        /// <summary>
        /// PC首页图片定制
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public IList<WidgetConfig> PictureWidgetConfigList(int storeId, string code = "index_pic_area")
        {
            var widget = WidgetManager.GetWidget(storeId, code);
            if (widget == null) return null;

            var list = WidgetManager.GetConfigList(widget.WId);
            return list;
        }

        /// <summary>
        /// 内容组件，获取首页的所有内容列表
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public IList<object> NewsWidgetConfigList(int storeId, string code = "pc_index_news")
        {
            var list = new List<object>();
            //项列表
            var widgetList = WidgetManager.GetWidgetList(storeId, true).Where(x => x.Code == code).ToList();

            foreach (var item in widgetList)
            {
                //项对应的配置列表
                var configList = WidgetManager.GetConfigList(item.WId);

                foreach (var config in configList)
                {
                    LinkValue model = JsonConvert.DeserializeObject<LinkValue>(config.LinkValue);
                    if (model == null)
                        continue;

                    //横排一行4个，竖排20个,(默认横排图片排版)
                    int pageSize = config.DisplayType == 2 ? 20 : 4;
                    list.Add(new
                    {
                        Wid = item.WId,
                        LinkId = model.Id,
                        LinkType = model.LinkType,
                        ShowImg = config.ShowImg,
                        LinkName = model.Name,
                        DisplayType = config.DisplayType,
                        NewsList = News.GetNewsList(pageSize, 1, "newstypeid=" + model.Id, item.StoreId)
                    });
                }
            }

            return list;
        }

        /// <summary>
        /// 获取顶部轮播图片信息
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        public IList<WidgetConfig> Getwidgetconfig(int wid)
        {
            if (wid < 1)
                throw new Exception("缺少wid参数");
            return WidgetManager.GetConfigList(wid);
        }

        /// <summary>
        /// 获取图片组件
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="postion"></param>
        /// <returns></returns>
        public IList<WidgetConfig> GetIndexpictureConfig(int wid, int postion)
        {
            return WidgetManager.GetConfigShowList(wid, postion);
        }

        /// <summary>
        /// 获取分类导航数据
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="postion"></param>
        /// <returns></returns>
        public IList<WidgetConfig> Getwidgetconfiglist(int wid, int postion)
        {
            return WidgetManager.GetConfigShowList(wid, postion);
        }

        /// <summary>
        /// 获取商品的太阳码
        /// </summary>
        /// <returns></returns>
        public ProductExtend ProductAppCode(int pid)
        {
            return ProductExtendManager.Get(pid);
        }

        /// <summary>
        /// 店铺配置信息
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public object GetInfo(int storeId)
        {
            if (storeId < 1)
                throw new Exception("缺少店铺参数");

            //店铺信息
            var info = Stores.GetStoreById(storeId);
            if (info == null) { return ""; }
            var logo = info != null ? string.Format("http://static.711688.net.cn/upload/store/{0}/logo/source/{1}", storeId, info.Logo) : "/images/1loog.png";

            //图片路径
            Dictionary<string, string> imgPath = new Dictionary<string, string>();
            imgPath.Add("widget", "http://static.711688.net.cn/upload/store/{storeid}/widget/");
            imgPath.Add("product", "http://static.711688.net.cn/upload/store/{storeid}/product/show/source/");
            imgPath.Add("news", "http://static.711688.net.cn/upload/news/");
            imgPath.Add("AppCode", "");
            //获取省市县：
            var region = Regions.GetRegionById(info.RegionId);
            if (region == null) { return ""; }
            var name = region.Name == null ? "" : region.Name;//省市
            var provincename = region.ProvinceName == null ? "" : region.ProvinceName;
            var cityname = region.CityName == null ? "" : region.CityName;
            var adress = info.Address == null ? "" : info.Address;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}{1}{2}{3}", provincename, cityname, name, adress);
            var obj = new
            {
                Storeid = info.StoreId,
                SiteLogo = logo,    //网站LOGO
                ImgDomain = "http://static.711688.net.cn/",
                ImgPath = imgPath,
                Address = sb.ToString(),
                QQ = info.QQ == null ? "" : info.QQ,
                Phone = info.Phone == null ? "" : info.Phone,
                Mobile = info.Mobile == null ? "" : info.Mobile,
                Fax = info.Fax == null ? "" : info.Fax,
                WeApp_Qrcode = info.WeApp_Qrcode == null ? "" : info.WeApp_Qrcode,
                WeService_Qrcode = info.WeService_Qrcode == null ? "" : info.WeService_Qrcode,
                Email = info.Email == null ? "" : info.Email,
                WebSite = info.WebSite == null ? "" : info.WebSite
            };
            return obj;
        }

        /// <summary>
        /// 根据小程序网站的域名获取店铺ID
        /// </summary>
        /// <param name="website"></param>
        /// <returns></returns>
        public int GetStoreIdByWebsite(string website)
        {
            return StoreInfoManager.GetStoreIdByWebSite(website);
        }
    }
}